package com.demo.filter;

import com.demo.pojo.User;
import com.demo.service.UserService;
import com.demo.service.imp.UserServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 拦截的访问登录页面，判断用户是否携带了自动登录相关的Cookie数据，若没有携带，直接放行，让去登录页面
 * 若携带自动登录的Cookie，这时需要判断cookie中的数据是否正确，若不正确，继续放行，
 * 若数据判断正确，直接给用户返回登录成功之后的页面（首页）
 */
@WebFilter("/login.html")
public class AutoLoginFilter implements Filter {
    private UserService userService = new UserServiceImpl();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("用户正在访问登录页面，被拦截到了。。。。");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Cookie[] cookies = req.getCookies();
        // 获取和账号与密码相关的cookie数据
        Cookie userAccount = getCookie(cookies, "userAccount");
        Cookie userPwd = getCookie(cookies, "userPwd");
        if(userAccount != null && userPwd != null){
            User user = this.userService.login(userAccount.getValue(), userPwd.getValue());
            if(user == null){
                // 用户携带了账号和密码的Cookie，但是账号和密码是错误的，也需要放行
                chain.doFilter(req, response);
            }else{
                // 直接跳转到成功之后的页面
                resp.sendRedirect("/demo/index.html");
            }
        }else{
            chain.doFilter(req, response);
        }
    }
    private Cookie getCookie(Cookie[] cookies, String name){
        if(cookies == null || cookies.length == 0){
            return null;
        }
        for(Cookie cookie : cookies){
            if(name.equals(cookie.getName())){
                return cookie;
            }
        }
        return null;
    }
}
